package com.hc.testLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hc.R;
import com.hc.R.layout;
import com.hc.R.menu;
import com.hc.activity.util.ActivityApplicationUtil;
import com.hc.logdbservice.LogDBManager;
import com.hc.model.TestLogModel;
import com.hc.util.EquUtil;
import com.hc.util.FileUtil;
import com.hc.util.ZipFileUtil;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;

import android.app.DownloadManager.Query;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class TestLogActivity extends Activity {
	 private LogDBManager mgr;  
	 private ListView listView;  
	 private List<TestLogModel> logs;
		private  String[] logFileArray ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 当前的activity加入到关闭集合中
				ActivityApplicationUtil.getInstance().addActivity(this);
				// 设置没有title
				requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_test_log);
		listView = (ListView) findViewById(R.id.logListView);  
        //初始化DBManager  
        mgr = new LogDBManager(this);  
    	Log.e("sql", "初始化LogManager");
        Button btn = (Button) findViewById(R.id.query_btn);//给刷新按钮添加事件
        btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				queryLogs();
		        iniData();
				Toast.makeText(TestLogActivity.this.getApplicationContext(), "刷新完成", 0).show();
				
			}
		});
        Button delAll_btn = (Button) findViewById(R.id.delAll_btn);//给刷新按钮添加事件
        delAll_btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mgr.delAll();
				deleteFiles();
				Toast.makeText(TestLogActivity.this.getApplicationContext(), "清空完成", 0).show();
				queryLogs();
			}
		});
        queryLogs();
        iniData();
        
        
        listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				
				selectLog(arg2);
			}
		});
        
	}
	private void deleteFiles() {
		
		String[] files = FileUtil.readfile2(EquUtil.MYFILEPATH2);
		
		for(String str:files){
			
			if(str.indexOf("temp")==-1&&str.indexOf("config")==-1){
				FileUtil.delFileDirOrFile(EquUtil.MYFILEPATH2+"/"+str);
			}
			
		}
	}
	private void iniData() {
		
		FileUtil.fileList.clear();
		 FileUtil.readfiles(EquUtil.MYFILEPATH2);

		
	}
	protected void selectLog(int arg2) {
		
		TestLogModel model = logs.get(arg2);
		
		String filePath = 	getFilePath( model.getFormName());
		

		if(filePath==null||filePath.equals("")){
			
			new AlertDialog.Builder(this).setTitle("提示").setMessage("没有找到日志文件")
			.setPositiveButton("确定", null).create().show();
			
		}else{
			
			showFileName(filePath);
			
			
		}
		
	}
	
	private void showFileName(final String filePath) {

		Map<String ,Long> fileMap = null;
		try {
			fileMap = ZipFileUtil.readZipFileName(filePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if ( fileMap.size() > 0 )
		{
			logFileArray= new String[fileMap.size()];
			int i =0;
			for(Object o : fileMap.keySet()){ 
//				Long zie = fileMap.get(o); 
				logFileArray[i] = o.toString();
				i++;
			} 
			
			 new AlertDialog.Builder(this)
		       .setTitle("选择日志文件（文件总数："+fileMap.size()+"）")
		       .setItems(logFileArray, new DialogInterface.OnClickListener() { // 列表内容和点击事件
		        
		        @Override
		        public void onClick(DialogInterface dialog, final int whichPlace) {
		        	

					
					String selectdStr = logFileArray[whichPlace];
					String[] results = selectdStr.split("      ");
					selectLogFile(results[0],filePath);
				
		        	
		        }}).show();
		       
			
		}else
		{
			new AlertDialog.Builder(this).setTitle("提示").setMessage("没有找到日志文件")
			.setPositiveButton("确定", null).create().show();
		}
		
	
	}

	protected void selectLogFile(String logFileName, String logFilePath) {

		TestLogFileBean  fileContent = null;
 		try {
 			fileContent = ZipFileUtil.readZipFile(logFileName,logFilePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
 		
 		if(fileContent !=null ){
 			
 			Intent intent = new Intent(TestLogActivity.this,ShowLogFileActivity.class);
 			intent.putExtra("bean", fileContent);
 			startActivity(intent);
 		}else{
 			
 			new AlertDialog.Builder(this).setTitle("提示").setMessage("日志文件没有内容")
			.setPositiveButton("确定", null).create().show();
 		}
		
	
		
	}

	private String getFilePath(String name){
		
		for(Object o:FileUtil.fileList){
			if(o.toString().indexOf(name)!=-1){
				return o.toString();
			}
		}
		return "";
	}
	private void getData(){
		
		logs	= mgr.getLogModels(); 
	}
	
	private void queryLogs() {
		
		getData();
		 
	        ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();  
	        for (TestLogModel log : logs) {  
	            HashMap<String, String> map = new HashMap<String, String>();  
	            map.put("name", log.getFormName());  
	            map.put("info", "开始时间："+log.getStarTime()+" 连接AP： "+log.getApName() +" 测试的信道："+log.getTestChannel()+ " 结束时间： " + log.getStopTime());  
	            list.add(map);  
	        }  
	        SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2,  
	                    new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2});  
	        listView.setAdapter(adapter); 
	}

	


}
